//
//  simViewController.m
//  simens
//
//  Created by amy zhang on 12-7-16.
//  Copyright (c) 2012年 yst. All rights reserved.
//

#import "simLoginViewController.h"
#import "ASIHTTPRequest.h"
#include <sys/socket.h> // Per msqr 
#include <sys/sysctl.h> 
#include <net/if.h> 
#include <net/if_dl.h>

@interface simLoginViewController ()<UITextFieldDelegate,MBProgressHUDDelegate>

-(void) loginbuttonPress;
-(void) missKeyBoard;

@property (nonatomic, strong) UITextField* userNameTextField;
@property (nonatomic, strong) UITextField* userPassWordTextField;
@property (nonatomic,strong) NSString *loginMoblie;
@property (nonatomic,strong) NSString *loginName;
@property (nonatomic,strong) UIButton* savePwdBt;
@end

@implementation simLoginViewController


@synthesize userNameTextField = _userNameTextField;
@synthesize userPassWordTextField = _userPassWordTextField;
@synthesize loginName=_loginName;
@synthesize loginMoblie=_loginMoblie;
@synthesize loginDelegete;
@synthesize savePwdBt;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    [self.navigationController.navigationBar setHidden:YES];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"login.png"]]];
    
    [self.view setFrame:CGRectMake(0, 0, 320, 480)];
    //self.title=@"登录";
    UIButton* backBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBt setFrame: CGRectMake(0, 0, 320, 480)];
    [backBt setBackgroundColor:[UIColor clearColor]];
    //定义点击时的响应函数
	[backBt addTarget:self action:@selector(missKeyBoard) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:backBt];
    
    // Button 代码参照这里写
    UIButton* loginBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBt setFrame:CGRectMake(180, 220, 105, 44)];
    [loginBt setImage:[UIImage imageNamed:@"longinButton_up.png"] forState:UIControlStateNormal];
    [loginBt setImage:[UIImage imageNamed:@"longinButton_down.png"] forState:UIControlStateHighlighted];
    [loginBt setBackgroundColor:[UIColor clearColor]];
    
    
    //定义点击时的响应函数
	[loginBt addTarget:self action:@selector(loginbuttonPress) forControlEvents:UIControlEventTouchUpInside]; 
    
    [self.view addSubview:loginBt];

    self.userNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(86, 145, 190, 30)];
    //[self.userNameTextField setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    self.userNameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;  
    [self.userNameTextField setPlaceholder:@"点击输入用户名"];
    self.userNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;//编辑时，可以右边按钮全删除内容
    [self.userNameTextField setBorderStyle:(UITextBorderStyleRoundedRect)];
    NSString *mobile=[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginName"];
    [self.userNameTextField setText:mobile];
    [self.userNameTextField setKeyboardType:UIKeyboardTypePhonePad];
    
    [self.userNameTextField setDelegate:self];
    
    //首字母小写
    [self.userNameTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    
    //[self.userNameTextField setBackgroundColor:[UIColor redColor]];
    [self.view addSubview: self.userNameTextField];
    
    self.userPassWordTextField = [[UITextField alloc] initWithFrame:CGRectMake(86, 185, 190, 30)];
    self.userPassWordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;  
    [self.userPassWordTextField setPlaceholder:@"点击输入密码"];
    self.userPassWordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;//编辑时，可以右边按钮全删除内容
    [self.userPassWordTextField setDelegate:self];
    [self.userPassWordTextField setSecureTextEntry:YES];
    //[self.userPassWordTextField setBackgroundColor:[UIColor redColor]];
    [self.userPassWordTextField setBorderStyle:(UITextBorderStyleRoundedRect)];
    [self.view addSubview: self.userPassWordTextField];
    
    // 记住密码状态
    NSString *savePwdStat=[[NSUserDefaults standardUserDefaults]objectForKey:@"savePwdStat"];
    
    savePwdBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [savePwdBt setFrame:CGRectMake(80, 225, 26, 24)];
    
    if([@"y" isEqualToString:savePwdStat]){
        [savePwdBt setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
    }
    
    [savePwdBt setBackgroundColor:[UIColor clearColor]];
    [savePwdBt addTarget:self action:@selector(savePwdBtPress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:savePwdBt];
    
    if([@"y" isEqualToString:savePwdStat]){
        NSString *pwd=[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"];
        [self.userPassWordTextField setText:pwd];
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:@"http://eiip.mobilitychina.com:8080/openApiPlatform/Service/rs/siemensService" forKey:@"WebserviceUrl"];//10.91.2.1461.164.42.175
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSLog(@"mac address is %@",self.macaddress);
}

// Return the local MAC addy 
// Courtesy of FreeBSD hackers email list 
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb. 
- (NSString *)macaddress{ 
    
    int                 mib[6]; 
    size_t              len; 
    char                *buf; 
    unsigned char       *ptr; 
    struct if_msghdr    *ifm; 
    struct sockaddr_dl  *sdl; 
    
    mib[0] = CTL_NET; 
    mib[1] = AF_ROUTE; 
    mib[2] = 0; 
    mib[3] = AF_LINK; 
    mib[4] = NET_RT_IFLIST; 
    
    if ((mib[5] = if_nametoindex("en0")) == 0) { 
        printf("Error: if_nametoindex error\n"); 
        return NULL; 
    } 
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { 
        printf("Error: sysctl, take 1\n"); 
        return NULL; 
    } 
    
    if ((buf = malloc(len)) == NULL) { 
        printf("Could not allocate memory. error!\n"); 
        return NULL; 
    } 
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { 
        printf("Error: sysctl, take 2"); 
        free(buf); 
        return NULL; 
    } 
    
    ifm = (struct if_msghdr *)buf; 
    sdl = (struct sockaddr_dl *)(ifm + 1); 
    ptr = (unsigned char *)LLADDR(sdl); 
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",  
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; 
    free(buf); 
    
    return outstring; 
}

-(void) loginbuttonPress {
    
    [self missKeyBoard];
    
    if ([self.userNameTextField.text isEqualToString:@""] || self.userNameTextField.text == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"用户名为空" message:@"请输入用户名"
                                                       delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        
        //自动启动用户名编辑框
        [self.userNameTextField becomeFirstResponder]; 
    }
    else if ([self.userPassWordTextField.text isEqualToString:@""] || self.userPassWordTextField.text == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"密码为空" message:@"请输入密码"
                                                       delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        
        //自动启动密码编辑框
        [self.userPassWordTextField becomeFirstResponder]; 
    }
    else {
        [self showMbprogress];
        //登陆
        self.loginMoblie=[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"];
        self.loginName=[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginName"];
        if(self.loginName==nil){
            self.loginMoblie=self.userNameTextField.text;
        } else {
            // modify by xujiakun
            if (![self.loginName isEqualToString: self.userNameTextField.text]) {
                self.loginMoblie=self.userNameTextField.text;
            }
        }
        
        NSLog(@"login mobile is:%@",self.loginMoblie);
        NSString* u=[NSString stringWithFormat:@"%@/siemensLogin?mobile=%@&pwd=%@&mac=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],self.loginMoblie,self.userPassWordTextField.text,self.macaddress];    
        NSURL *url = [NSURL URLWithString:u];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request startSynchronous];
        NSError *error = [request error];
        if (!error) {
            NSString *response = [request responseString];
            NSLog(@"login  is :%@",response);
            
            [self performSelector:@selector(LoginCallBack:) withObject:response afterDelay:2];//30秒后检查
            
        }
        
    }
}

-(void) LoginCallBack:(NSString*)response {
    
    [self hideMbProgress];
    //13470731979 90 91
    
    //姓名&标示(标示：1.帐号与设备不匹配 2.账号不存在 3.密码错误 4. 登陆成功 5.您的设备已绑定其他手机号码)
    NSString *flag=[response substringFromIndex:response.length-1]; 
    if([flag isEqualToString:@"4"]==YES){//登陆成功
        //保存登陆帐号密码
        NSString *str=[response substringToIndex:response.length-2];
        NSRange r=[str rangeOfString:@"&"];
        NSString *name=[response substringToIndex:r.location];
        //NSLog(@"%d ,%@",r.location,name);
        
        [[NSUserDefaults standardUserDefaults] setObject:self.loginMoblie forKey:@"LoginMobile"];
        [[NSUserDefaults standardUserDefaults] setObject:self.userPassWordTextField.text forKey:@"LoginPassword"];
        [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"LoginName"];
		[[NSUserDefaults standardUserDefaults] synchronize];
         
        [loginDelegete LoginSuccess];
        
    }else {
        NSString * mess=@"";
        if([flag isEqualToString:@"1"]){
            mess=@"帐号与该设备不匹配";
        }else if([flag isEqualToString:@"2"]){
            mess=@"您的账号不存在";
        }else if([flag isEqualToString:@"3"]){
            mess=@"密码错误";
        }else if([flag isEqualToString:@"5"]){
            mess=@"您的设备已绑定其他手机号码";
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:mess
                                                       delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
    }
}

-(void) missKeyBoard {
    
    [self.userNameTextField resignFirstResponder]; 
    [self.userPassWordTextField resignFirstResponder]; 
}


//iPad键盘的Retuan...电脑的回车键
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == self.userNameTextField) {
        
        //用户名输入完成，点击键盘Return
        //自动弹出密码输入
        [self.userPassWordTextField becomeFirstResponder];
        
    }else if (textField == self.userPassWordTextField) {
        //启动登陆
        [self loginbuttonPress];
    }
    return YES;
}

-(void) savePwdBtPress {
    NSString *savePwdStat=[[NSUserDefaults standardUserDefaults]objectForKey:@"savePwdStat"];
    
    if ([@"y" isEqualToString:savePwdStat]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"savePwdStat"];
        [savePwdBt setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:@"y" forKey:@"savePwdStat"];
        [savePwdBt setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
